/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lansupportclient;

import ObjectHandler.LanSupportMessage;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import javax.imageio.ImageIO;

/**
 *
 * @author Quan
 */
public class SendScreen implements Runnable {

    private boolean _continue = true;
    private Socket sendSocket;
    private String Type;

    public SendScreen(Socket sendSocket) {
        this.sendSocket = sendSocket;
        this.Type = LanSupportMessage.ViewScreenImage;
    }

    public SendScreen(Socket sendSocket, String type) {
        this.sendSocket = sendSocket;
        this.Type = type;
    }

    public void setContinue(boolean _continue) {
        this._continue = _continue;
    }

    @Override
    public void run() {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(this.Type);
        while (_continue) {
            byte[] imageData = CaptueScreen();
            if (imageData != null) {
                lanSupportMessage.setData(imageData);
                lanSupportMessage.Send(sendSocket);
            } else {
                _continue = false;
            }
        }
    }

    private byte[] CaptueScreen() {
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        BufferedImage bufferedImage = null;
        byte[] imageInByte = null;
        Robot robot;
        try {
            robot = new Robot();
            bufferedImage = robot.createScreenCapture(screenRect);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", baos);
            baos.flush();
            imageInByte = baos.toByteArray();
        } catch (IOException | AWTException ex) {
            return null;
        }
        return imageInByte;
    }
}
